import { Loading } from 'element-ui'
import { loginCheck, logout } from '@/api/sys/auth'
import { getToken, setToken, removeToken } from '@/utils/token'

const state = {
  isCollapse: false,
  userInfo: null,
  token: getToken()
}

const mutations = {
  menuChange(state) {
    state.isCollapse = !state.isCollapse
  },
  SET_USER(state, userInfo) {
    state.userInfo = userInfo == null ? null : userInfo.userInfo
  },
  SET_TOKEN(state, token) {
    setToken(token)
  }
}

const actions = {
  handleMenuChange(context) {
    context.commit('menuChange')
  },
  userLogin({ commit }, userInfo) {
    return new Promise(async (resolve) => {
      await loginCheck(userInfo)
        .then((res) => {
          // 登录校验
          const { state, obj } = res
          if (state) {
            commit('SET_TOKEN', obj.token)
          }
          resolve(res)
        })
    })
  },
  setUser({ commit }, userInfo) {
    commit('SET_USER', userInfo)
  },
  logUserout({ commit }) {
    let loadingInstance = Loading.service({ fullscreen: true, text: '系统退出中。。。' })
    return new Promise((resolve, reject) => {
      logout().then(() => {
        removeToken()
        commit('SET_USER', null)
        location.reload()
        loadingInstance.close()
      })
    })
  }
}

const getters = {
  userInfo(state) {
    if (state.userInfo) {
      return state.userInfo
    }
    return {}
  },
  avatarImg(state, getter) {
    return getter.userInfo.avatarImg
  },
  realName(state, getter) {
    return getter.userInfo.realName
  },
  updateTime(_, getter) {
    return '上次登陆时间：' + (getter.userInfo.updateTime)
  },
  roles(_, getter) {
    if (getter.userInfo) {
      const { authorities = [] } = getter.userInfo
      return authorities.map(item => item.authority)
    }
    return ['test']
  },
  depName(_, getter) {
    return getter.userInfo.depName
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
